
package Map

import(
	"fmt"
	"sanguo/node/table/excel"
	"sanguo/node/table/excel/table"
	"strconv"

	"github.com/tealeg/xlsx"
)

func readInt32(v string) int32 {
	return int32(readFloat(v))
}

func readFloat(v string) float64 {
	vv,err := strconv.ParseFloat(v,64)
	if nil != err {
		panic(err)
	}
	return vv
}

func readBool(str string) bool {
    b, err := strconv.ParseBool(str)
	if nil != err {
		panic(err)
	}
    return b
}

func readStr(v string) string {
	return fmt.Sprintf("%s",v)
}

type DefaultPosition_ struct {
	X int32
	Y int32
	Z int32
}

type Map struct {
	ID int32
	Type int32
	Length int32
	Width int32
	DefaultPosition DefaultPosition_
	DefaultRotation int32
}

func readDefaultPosition(value string) DefaultPosition_ {

	DefaultPosition := DefaultPosition_{}
	r := excel.Split(value,",")

	DefaultPosition.X = readInt32(r[0][0])

	DefaultPosition.Y = readInt32(r[0][1])

	DefaultPosition.Z = readInt32(r[0][2])
		
	return DefaultPosition
}

type Table struct {
	IDMap map[int32]*Map
	tmpIDMap map[int32]*Map
	xlsxName string
}

var Table_ Table

func getIdxByName(names *xlsx.Row, name string) int {
	for i, v := range names.Cells {
		if v.String() == name {
			return i
		}
	}
	return -1
}

func init() {
	Table_.xlsxName = "Map.xlsx"
	Table_.IDMap = make(map[int32]*Map)
	Table_.tmpIDMap = make(map[int32]*Map)

	table.AddTable(&Table_)
}


func (this *Table) Load(path string) {

	excel.EmptyFunc()

    xlFile, err := xlsx.OpenFile(path + this.xlsxName)
    if err != nil {
		panic(err)
    }

    sheet := xlFile.Sheets[0]
    names := sheet.Rows[1]
    rows  := sheet.Rows[3:]

    for _,row := range(rows) {
    	if len(row.Cells) > 0 && row.Cells[0].String() != "" {
    		ele := &Map{}
    	
		ele.ID = readInt32(row.Cells[getIdxByName(names, "ID")].String())
		this.tmpIDMap[ele.ID] = ele
		ele.Type = readInt32(row.Cells[getIdxByName(names, "Type")].String())
		ele.Length = readInt32(row.Cells[getIdxByName(names, "Length")].String())
		ele.Width = readInt32(row.Cells[getIdxByName(names, "Width")].String())
		ele.DefaultPosition = readDefaultPosition(row.Cells[getIdxByName(names, "DefaultPosition")].String())
		ele.DefaultRotation = readInt32(row.Cells[getIdxByName(names, "DefaultRotation")].String())

		}
    }

    this.IDMap = this.tmpIDMap
 
}

